<template>
	<view class="page-news">
		<!-- #ifdef APP-NVUE -->
		<list ref="list" class="listview">
			<refresh :display="refreshing" @refresh="onrefresh" @pullingdown="onpullingdown"></refresh>
			<cell v-for="(item, index) in dataList" :key="item.id">
				<news-item :newsItem="item" @close="closeItem(index)" @click="goDetail(item)"></news-item>
			</cell>
			<cell v-if="isLoading || dataList.length > 4">
				<view class="loading-more">
					<text class="loading-more-text">{{loadingText}}</text>
				</view>
			</cell>
		</list>
		<!-- #endif -->
		<!-- #ifndef APP-NVUE -->
		<scroll-view class="listview" style="flex: 1;" enableBackToTop="true" scroll-y @scrolltolower="loadMore()">
			<view v-for="(item, index) in dataList" :key="item.id">
				<news-item :newsItem="item" @close="closeItem(index)" @click="goDetail(item)"></news-item>
			</view>
			<view class="loading-more" v-if="isLoading || dataList.length > 4">
				<text class="loading-more-text">{{loadingText}}</text>
			</view>
		</scroll-view>
		<!-- #endif -->
		<no-data class="no-data" v-if="isNoData" @retry="loadMore"></no-data>
	</view>
</template>

<script>
	import {
		friendlyDate
	} from '@/common/util.js';

	import newsItem from './news-item.vue';
	import uniLoadMore from '@/components/uni-load-more.vue';
	import noData from '@/components/nodata.vue';

	export default {
		components: {
			uniLoadMore,
			noData,
			newsItem
		},
		props: {
			rank: {
				type: [Number, String],
				default: 1,
			},
			nid: {
				type: [Number, String],
				default: ''
			}
		},
		data() {
			return {
				page: 1,
				dataList: [],
				navigateFlag: false,
				pulling: false,
				refreshing: false,
				refreshFlag: false,
				refreshText: "",
				isLoading: false,
				loadingText: '加载中...',
				isNoData: false,
				angle: 0,
				loadingMoreText: {
					contentdown: '',
					contentrefresh: '',
					contentnomore: ''
				},
				refreshIcon: ""
			}
		},
		created() {
			this.pullTimer = null;
			this.requestParams = {
				columnId: this.nid,
				minId: 0,
				pageSize: 10,
				column: 'id,post_id,title,author_name,cover,published_at,comments_count'
			};

			this._isWidescreen = false;
			// #ifdef H5
			var mediaQueryOb = uni.createMediaQueryObserver(this)
			mediaQueryOb.observe({
				minWidth: 768
			}, matches => {
				this._isWidescreen = matches;
			})
			// #endif
		},
		methods: {
			loadData(refresh) {
				if (this.isLoading) {
					return;
				}

				this.isLoading = true;
				this.isNoData = false;

				let startTime = new Date();
				
				let param = {
					cmd: 'LunTan_GetInfo',
					nUid: uni.getStorageSync('uid') || 0,
					nPage: this.page,
					nRank: this.rank
				}
				
				uni.request({
					// url: this.$host + 'api/news',
					// url: 'https://jianxia.mazhoudao.com/api/?data={%22cmd%22:%22LunTan_GetInfo%22}',
					url: 'https://jianxia.mazhoudao.com/api',
					data: {
						data: param
					},
					success: (result) => {
						let endTime = new Date();
						const data = result.data;
						const data_list = Object.values(data).map((news) => {
							if (typeof news === 'object') {
								return {
									id: news.nID,
									newsid: news.nID,
									datetime: friendlyDate(new Date(news.create_time.replace(/\-/g, '/')).getTime()),
									title: news.sTitle || '',
									content: news.sContent || '',
									image_url: news.cover || '',
									source: news.author_name || '',
									comment_count: news.nComment || '0',
									praise_count: news.nPraise || '0',
									is_collect: news.bPraise >= 1,
									avatar: news.sHeadimgurl,
									nickname: news.sNickName,
									images: []
								};
							}
						});
						
						this.isNoData = (data_list.length <= 0);

						if (refresh) {
							this.dataList = data_list;
							this.page = 1;
						} else {
							this.dataList = this.dataList.concat(data_list);
							this.page += 1;
						}

						if (this.dataList.length > 0 && this._isWidescreen && this.dataList.length <= 10) {
							this.goDetail(this.dataList[0]);
						}
					},
					fail: (err) => {
						if (this.dataList.length == 0) {
							this.isNoData = true;
						}
					},
					complete: (e) => {
						this.isLoading = false;
						if (refresh) {
							this.refreshing = false;
							this.refreshFlag = false;
							this.refreshText = "已刷新";
							if (this.pullTimer) {
								clearTimeout(this.pullTimer);
							}
							this.pullTimer = setTimeout(() => {
								this.pulling = false;
							}, 1000);
						}
					}
				});
			},
			loadMore(e) {
				this.loadData();
			},
			clear() {
				this.dataList.length = 0;
				this.requestParams.minId = 0;
			},
			goDetail(detail) {
				if (this._isWidescreen) { //若为宽屏，则触发右侧详情页的自定义事件
					uni.$emit('updateDetail', {
						detail: encodeURIComponent(JSON.stringify(detail))
					})
				} else {
					uni.navigateTo({
						url: './detail?query=' + encodeURIComponent(JSON.stringify(detail))
					});
				}
			},
			closeItem(index) {
				uni.showModal({
					content: '不感兴趣？',
					success: (res) => {
						if (res.confirm) {
							this.dataList.splice(index, 1);
						}
					}
				})
			},
			refreshData() {
				if (this.isLoading) {
					return;
				}
				this.pulling = true;
				this.refreshing = true;
				this.refreshText = "正在刷新...";
				this.loadData(true);
			},
			onrefresh(e) {
				this.refreshData();
				// #ifdef APP-NVUE
				this.$refs.list.resetLoadmore();
				// #endif
			},
			onpullingdown(e) {
				if (this.refreshing) {
					return;
				}

				// var angle = (e.pullingDistance) / e.viewHeight * 180;
				// if (angle > 180) {
				// 	angle = 180;
				// }
				// tab.angle = angle;

				this.pulling = false;
				if (Math.abs(e.pullingDistance) > Math.abs(e.viewHeight)) {
					this.refreshFlag = true;
					this.refreshText = "释放立即刷新";
				} else {
					this.refreshFlag = false;
					this.refreshText = "下拉可以刷新";
				}
			},
			newGuid() {
				let s4 = function() {
					return (65536 * (1 + Math.random()) | 0).toString(16).substring(1);
				}
				return (s4() + s4() + "-" + s4() + "-4" + s4().substr(0, 3) + "-" + s4() + "-" + s4() + s4() + s4())
					.toUpperCase();
			}
		}
	}
</script>

<style scoped>
	.no-data {
		flex: 1;
		position: absolute;
		left: 0;
		top: 0;
		right: 0;
		bottom: 0;
		z-index: 10;
	}

	.page-news {
		flex: 1;
		flex-direction: column;
		position: absolute;
		left: 0;
		top: 0;
		right: 0;
		bottom: 0;
	}

	.listview {
		position: absolute;
		left: 0;
		top: 0;
		right: 0;
		bottom: 0;
		/* #ifndef APP-NVUE */
		display: flex;
		flex-direction: column;
		/* #endif */
		/* #ifndef MP-ALIPAY */
		flex-direction: column;
		/* #endif */
	}

	.refresh {
		justify-content: center;
	}

	.refresh-view {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		width: 750rpx;
		height: 64px;
		flex-direction: row;
		flex-wrap: nowrap;
		align-items: center;
		justify-content: center;
	}

	.refresh-icon {
		width: 32px;
		height: 32px;
		transition-duration: .5s;
		transition-property: transform;
		transform: rotate(0deg);
		transform-origin: 15px 15px;
	}

	.refresh-icon-active {
		transform: rotate(180deg);
	}

	.loading-icon {
		width: 28px;
		height: 28px;
		margin-right: 5px;
		color: gray;
	}

	.loading-text {
		margin-left: 2px;
		font-size: 16px;
		color: #999999;
	}

	.loading-more {
		align-items: center;
		justify-content: center;
		padding-top: 14px;
		padding-bottom: 14px;
		text-align: center;
	}

	.loading-more-text {
		font-size: 28upx;
		color: #999;
	}
</style>
